package com.itheima.wemedia.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper,WmUser> implements WmUserService {



    /**
     * appId查询自媒体账号信息
     *
     * @param appUserId
     * @return
     */
    @Override
    public WmUser getByAppUserId(Integer appUserId) {
        WmUser wmUser = query().eq("ap_user_id", appUserId).one();
        return wmUser;
    }

    /**
     * 自媒体登录
     *
     * @param loginParam
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> loginParam) {
        String name = loginParam.get("name");
        String pwd = loginParam.get("password");
        if (StringUtils.isEmpty(name)||StringUtils.isEmpty(pwd)){
            throw new LeadNewsException("用户名或密码错误");
        }
        WmUser wmUser = query().eq("name", name).one();
        if (null == wmUser){
            throw new LeadNewsException("用户名或密码错误");
        }
        pwd += wmUser.getSalt();
        String Pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());

        if (!wmUser.getPassword().equals(Pwd)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        wmUser.setSalt(null);
        wmUser.setPassword(null);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("user",wmUser);
        return resultMap;
    }
}
